package com.pn.taikao.service.impl;

import com.pn.taikao.entity.Question;
import com.pn.taikao.mapper.QuestionMapper;
import com.pn.taikao.service.QuestionService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Service
public class QuestionServiceImpl implements QuestionService {

    private final QuestionMapper questionMapper;

    public QuestionServiceImpl(QuestionMapper questionMapper) {
        this.questionMapper = questionMapper;
    }

    @Override
    public Long createQuestion(Question question) {
        // 确保options不为null
        if (question.getOptions() == null) {
            question.setOptions(new HashMap<>());
        }
        
        // 设置默认难度
        if (!StringUtils.hasText(question.getDifficulty())) {
            question.setDifficulty("medium");
        }
        
        if (question.getCreateTime() == null) {
            question.setCreateTime(LocalDateTime.now());
        }
        if (question.getUpdateTime() == null) {
            question.setUpdateTime(LocalDateTime.now());
        }
        
        questionMapper.insert(question);
        return question.getId();
    }

    @Override
    public void updateQuestion(Question question) {
        // 确保options不为null
        if (question.getOptions() == null) {
            question.setOptions(new HashMap<>());
        }
        
        question.setUpdateTime(LocalDateTime.now());
        questionMapper.update(question);
    }

    @Override
    public void deleteQuestion(Long id) {
        questionMapper.deleteById(id);
    }

    @Override
    public Question getById(Long id) {
        return questionMapper.selectById(id);
    }

    @Override
    public List<Question> getByCourseId(Long courseId) {
        return questionMapper.selectByCourseId(courseId);
    }

    @Override
    public List<Question> list(String type, Long courseId, String difficulty, String content, int page, int size) {
        int offset = Math.max(page, 1);
        offset = (offset - 1) * Math.max(size, 1);
        return questionMapper.selectPage(type, courseId, difficulty, content, offset, size);
    }

    @Override
    public long count(String type, Long courseId, String difficulty, String content) {
        return questionMapper.count(type, courseId, difficulty, content);
    }
}

